﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 将图片写入数据库再读出
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            DialogResult result = ofd.ShowDialog();
            if (result != DialogResult.OK) return;
            tbPath.Text = ofd.FileName;
        }

        private void btnWrite2DataBase_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(tbPath.Text, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            Byte[] byData = br.ReadBytes((int)fs.Length);
            fs.Close();
            string conn = "server=.;database=abc;Uid=sa;Pwd=";
            SqlConnection myconn = new SqlConnection(conn);
            myconn.Open();
            //string str = "insert into tbFile (filename,myImage) values('测试文件',@file)";
            string str = "update tbMachinesIP set picSendFlag=1,pictureData=@pic";
            SqlCommand mycomm = new SqlCommand(str, myconn);
            mycomm.Parameters.Add("@pic", SqlDbType.VarBinary, byData.Length);
            mycomm.Parameters["@pic"].Value = byData;
            mycomm.ExecuteNonQuery();
            myconn.Close();
        }

        private void btnDataBase2File_Click(object sender, EventArgs e)
        {
            string conn = "server=.;database=abc;Uid=sa;Pwd= ";
            string str = "select myImage from tbFile where filename='测试文件' ";
            SqlConnection myconn = new SqlConnection(conn);
            SqlDataAdapter sda = new SqlDataAdapter(str, conn);
            DataSet myds = new DataSet();
            myconn.Open();
            sda.Fill(myds);
            myconn.Close();
            Byte[] Files = (Byte[])myds.Tables[0].Rows[0]["myImage"];
            BinaryWriter bw = new BinaryWriter(File.Open("D:\\DownData.exe", FileMode.OpenOrCreate));
            bw.Write(Files);
            bw.Close();
        }
    }
}
